package be.xios.projectquiz.cards;

import java.awt.Color; 
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.BorderFactory;
import javax.swing.JPanel;

/// <summary>
/// Dit is een jpanel die de LBALLS weergeven en hertekent 
/// </summary>
/// <author>Sebastian Kubski</author>
public class LoadingAnimation extends JPanel implements Runnable {

	private static final long serialVersionUID = 1L;
	private LBall []balls = new LBall[12];
	private int counter = 0;
	private Color matrixKleur = new Color(201,251,164);

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
			
		Graphics2D g2D=(Graphics2D) g;		
		g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

		generateBalls(this.getWidth()/2 - 10, this.getHeight()/2 - 10, 50);

		this.setBorder(BorderFactory.createLineBorder(Color.BLACK,3));
		
		for (int i = 0; i < balls.length; i++) {
				if ( counter == i ) {
					g.setColor(matrixKleur);
					balls[i].fill(g);
					g.setColor(Color.BLACK);
					balls[i].draw(g);	
					// effect 1
					if ( i < balls.length / 2 ) {
						g.setColor(matrixKleur);
						balls[i + (balls.length / 2 )].fill(g);
						g.setColor(Color.BLACK);
						balls[i + (balls.length / 2 )].draw(g);		
					}
					else {
						g.setColor(matrixKleur);
						balls[i - (balls.length / 2 )].fill(g);
						g.setColor(Color.BLACK);
						balls[i - (balls.length / 2 )].draw(g);
					} 
				} 
				//-- Als je deze else inschakelt ga je de overige ballen weergeven - effect 2
				else {				
					balls[i].draw(g);							
				}
		} // einde for	
	}
	@Override
	public void run() {
		try {
			while (true) {
				if ( counter == balls.length) {	
					counter = 0;
				}
				counter++;
				
				repaint();
				//-- sleep reduced van 400 nr 40 (hoeveelheid ballen is vergroot)
				Thread.sleep(200);
			}
		} 
		catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/// <summary>
	/// Deze method instantieert al de nodige LBALLS en berekent hun positie op denkbeeldige circel
	/// </summary>
	/// <parameters> cx cy - x en y locatie van de circel waarop de LBALL getekend worden, r is de straal van de circel</parameters>
	/// <author>Sebastian Kubski</author>
	public void generateBalls(int cx, int cy, int r) {
		int x,y;
		double a = 0, b = (360 / (double) balls.length);
		
		for (int i = 0; i < balls.length; i++) {		
			x = cx + (int) (r * Math.cos(Math.toRadians(a)));
			y = cy + (int) (r * Math.sin(Math.toRadians(a)));
			balls[i] = new LBall(x , y);
			a+=b;		
		}	
	}
}
